package cn.ming.wfchat.app.login;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.ming.wfchat.R;
import cn.ming.wfchat.app.AppService;
import cn.ming.wfchat.app.login.model.LoginResult;
import cn.ming.wfchat.app.main.MainActivity;
import cn.ming.wfchat.kit.ChatManagerHolder;
import cn.ming.wfchat.kit.WfcBaseActivity;
import cn.wildfirechat.remote.MD5Util;

public class SMSLoginActivity extends WfcBaseActivity {
    @BindView(R.id.loginButton)
    Button loginButton;
    @BindView(R.id.phoneNumberEditText)
    TextView phoneNumberEditText;
    @BindView(R.id.authCodeEditText)
    EditText authCodeEditText;
    @BindView(R.id.requestAuthCodeButton)
    TextView requestAuthCodeButton;
    @BindView(R.id.tv_type)
    TextView tv_type;
    @BindView(R.id.fl_authcode)
    FrameLayout flAuthcode;
    @BindView(R.id.passwordEditText)
    EditText passwordEditText;
    @BindView(R.id.fl_password)
    FrameLayout flPassword;


    @Override
    protected int contentLayout() {
        return R.layout.login_activity_sms;
    }

    @Override
    protected void afterViews() {
        setStatusBarTheme(this, false);
        //判断是否为旧设备
        validateImei();

    }

    /**
     * 判断是否为旧设备
     */
    void validateImei() {
        String account = getIntent().getStringExtra("account");
        phoneNumberEditText.setText(account);
        if (getIntent().getBooleanExtra("whetherPassword", true)) {
            //有设置密码
            if (getIntent().getBooleanExtra("whetherImei", true)) {
                //老设备
                passwordUI();
            } else {
                //新设备
                tv_type.setVisibility(View.GONE);
                codeUI();
            }

        } else {
            //没有设置密码
            tv_type.setVisibility(View.GONE);
            codeUI();

        }
    }

    /**
     * 密码登录
     */
    void passwordUI() {
        authCodeEditText.setText("");
        tv_type.setText("验证码登录");
        flPassword.setVisibility(View.VISIBLE);
        flAuthcode.setVisibility(View.GONE);
    }

    /**
     * 验证码登录
     */
    void codeUI() {
        passwordEditText.setText("");
        tv_type.setText("密码登录");
        flPassword.setVisibility(View.GONE);
        flAuthcode.setVisibility(View.VISIBLE);
    }

    @OnTextChanged(value = R.id.phoneNumberEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void inputPhoneNumber(Editable editable) {
        String phone = editable.toString().trim();
        if (phone.length() == 11) {
            requestAuthCodeButton.setEnabled(true);
        } else {
            requestAuthCodeButton.setEnabled(false);
            loginButton.setEnabled(false);
        }
    }

    @OnTextChanged(value = R.id.authCodeEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void inputAuthCode(Editable editable) {
        if (editable.toString().length() > 2) {
            loginButton.setEnabled(true);
        }
    }

    @OnTextChanged(value = R.id.passwordEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void inputPassword(Editable editable) {
        if (editable.toString().length() > 5) {
            loginButton.setEnabled(true);
        }
    }

    @OnClick(R.id.loginButton)
    void login() {
        String phoneNumber = phoneNumberEditText.getText().toString().trim();
        String authCode = authCodeEditText.getText().toString().trim();
        String passWord = passwordEditText.getText().toString().trim();

        loginButton.setEnabled(false);
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .content("登录中...")
                .progress(true, 100)
                .cancelable(false)
                .build();
        dialog.show();


        AppService.Instance().smsLogin(phoneNumber, authCode, MD5Util.getMD5String(passWord), new AppService.LoginCallback() {
            @Override
            public void onUiSuccess(LoginResult loginResult) {
                if (isFinishing()) {
                    return;
                }
                dialog.dismiss();
                //需要注意token跟clientId是强依赖的，一定要调用getClientId获取到clientId，然后用这个clientId获取token，这样connect才能成功，如果随便使用一个clientId获取到的token将无法链接成功。
                ChatManagerHolder.gChatManager.connect(loginResult.getUserId(), loginResult.getToken());
                SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
                sp.edit()
                        .putString("id", loginResult.getUserId())
                        .putString("token", loginResult.getToken())
                        .putString("keyid", loginResult.getAliyunOssSTSAK().getAccessKeyId())
                        .putString("secret", loginResult.getAliyunOssSTSAK().getAccessKeySecret())
                        .putString("bucket", loginResult.getAliyunOssSTSAK().getBucketName())
                        .putString("endpint", loginResult.getAliyunOssSTSAK().getEndpoint())
                        .putString("lockPassword", loginResult.getPasswordResp().getLockPassword())
                        .putBoolean("loginPassword", loginResult.getPasswordResp().isLoginPassword())
                        .putBoolean("lockPasswordEnable", loginResult.getPasswordResp().isLockPasswordEnable())
                        .putString("destroyPassword", loginResult.getPasswordResp().getDestroyPassword())
                        .putBoolean("destroyPasswordEnable", loginResult.getPasswordResp().isDestroyPasswordEnable())
                        .putBoolean("payPasswordEnable", loginResult.getPasswordResp().isPayPasswordEnable())
                        .apply();
                Intent intent = new Intent(SMSLoginActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
            }

            @Override
            public void onUiFailure(int code, String msg) {
                if (isFinishing()) {
                    return;
                }
                Toast.makeText(SMSLoginActivity.this, "登录失败：" + code + " " + msg, Toast.LENGTH_SHORT).show();
                dialog.dismiss();
                loginButton.setEnabled(true);
            }
        });
    }

    private Handler handler = new Handler();

    @OnClick(R.id.requestAuthCodeButton)
    void requestAuthCode() {
        requestAuthCodeButton.setEnabled(false);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isFinishing()) {
                    requestAuthCodeButton.setEnabled(true);
                }
            }
        }, 60 * 1000);

        Toast.makeText(this, "请求验证码...", Toast.LENGTH_SHORT).show();
        String phoneNumber = phoneNumberEditText.getText().toString().trim();

        AppService.Instance().requestAuthCode(phoneNumber, new AppService.SendCodeCallback() {
            @Override
            public void onUiSuccess() {
                Toast.makeText(SMSLoginActivity.this, "发送验证码成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onUiFailure(String msg) {
                Toast.makeText(SMSLoginActivity.this, "发送验证码失败: " + msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @OnClick(R.id.tv_type)
    void setTv_type() {
        if (tv_type.getText().toString().equals("密码登录")) {
            passwordUI();
        } else {
            codeUI();
        }
    }

}
